<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 订单结算ajax类
 * @package  ajax/comm/bill
 * @author   allen.qiang
 */

quanli_require('module/base/bill/billCheckout.class.php');
quanli_require('module/base/system/itemHandler.class.php');
quanli_require('module/base/goods/quanliGoods.class.php');
class ajax_checkout {

    private $bill_array; //购物车数组

    private $cust_buy_log; //会员购买记录

    private $pcustID; //会员号

    private $orders_code;    //会员下单编号

    private $source; //来源

    private $billType; //订单类型

    public function execute() {

        if (!isset($_REQUEST['source']) || !in_array($_REQUEST['source'], array('backend', 'web', 'wap', 'weixin', 'app'))) {
            returnJsonData('参数错误');
        }
        $this->source = $_REQUEST['source'];

        //会员购买记录
        if (!isset($_REQUEST['buy_log']) || empty($_REQUEST['buy_log'])) {
            returnJsonData('参数错误');
        }
        $this->cust_buy_log = $_REQUEST['buy_log'];

        //判断下单编号
        if(!isset($_REQUEST['orders_code']) || empty($_REQUEST['orders_code'])){
            returnJsonData('参数错误');
        }
        $this->orders_code = $_REQUEST['orders_code'];

        //订单的类型，不是必传项
        if(isset($_REQUEST['billType']) || !empty($_REQUEST['billType'])){
            $this->billType = $_REQUEST['billType'];
        }

        //判断会员号
        if (!isset($this->cust_buy_log['pcustID']) || !is_numeric($this->cust_buy_log['pcustID']) || $this->cust_buy_log['pcustID'] <= 0) {
            returnJsonData('参数错误');
        }

        $this->pcustID = $this->cust_buy_log['pcustID'];
        $this->getBillArray();

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 1: //查询收货地址、配送方式、支付方式、付款方式
                    $this->load();
                    break;

                case 2; //查询收货地址，并根据收货地址查询配送方式和支付方式
                    $this->loadFromAddress();
                    break;

                case 3: //查询配送方式，并根据配送方式查询支付方式
                    $this->loadFromSend();
                    break;

                case 4: //查询支付方式信息，并根据支付方式查询付现方式
                    $this->loadFromPay();
                    break;

                case 5: //查询付现方式信息
                    $this->loadFromPayment();
                    break;

                case 6: //查询发票信息
                    $this->loadFromInvoice();
                    break;

                case 7: //使用优惠券
                    $this->useCoupon();
                    break;

                case 8: //取消优惠券
                    $this->cancelCoupon();
                    break;

                case 9: //检查商品促销活动、检查订单促销、计算订单相关金额
                    $this->totalBill();
                    break;

                case 10: //检查促销渠道
                    $this->promotionChannel();
                    break;

                case 11: //使用积分
                    $this->usePoints();
                    break;

                case 12: //取消使用积分
                    $this->cancelPoints();
                    break;

                case 13: //使用代金卡
                    $this->useCard();
                    break;

                case 14: //取消使用代金卡
                    $this->cancelCard();
                    break;

                case 15: //检测代付订单
                    $this->checkBillPayingAgent();
                    break;

                case 16: //取消代付订单
                    $this->delBillPayingAgent();
                    break;

                case 17: //高级客服授权
                    $this->serviceAccredit();
                    break;

                case 18: //修改运费
                    $this->alterFreight();
                    break;

                case 19: //使用余额
                    $this->useBalace();
                    break;

                case 20: //取消使用余额
                    $this->cancelUseBalance();
                    break;

                default:
                    returnJsonData('参数错误');
                    break;

            }

        } else {

            returnJsonData('参数错误');

        }

    }

    /**
     * 获得购物车数据
     */
    private function getBillArray() {

        global $G_SHOP;

        $this->bill_array = $G_SHOP->sessionCache_get( 'checkout_backend_' . $this->orders_code, true );

    }

    /**
     * 保存购物车数据
     */
    private function setBillArray( $c = null, $data = null ) {

        global $G_SHOP;

        $G_SHOP->sessionCache_set( 'checkout_backend_' . $this->orders_code, $this->bill_array, 0, true);

        if (!is_null($c)) {

            $c['log'] = $this->cust_buy_log;

            returnJsonData('ok', 200, $c);

        } else {

            returnJsonData('ok', 200, $data);

        }

    }

    /**
     * 加载会员收货、配送方式、配送站、支付方式、付现方式、发票等信息
     * @throws Exception
     */
    private function load() {

        //实例订单结算类
        $billCheckout = new billCheckout();

        //发票
        $c['invoice'] = $billCheckout->getInvoiceList($this->bill_array['master'], $this->cust_buy_log);

        //收货地址
        if($this->billType && $this->billType==9 && $this->source=='backend'){//收货地址增加订单类型判断
           $this->bill_array['master']['billType']=9; 
        }
        $c['deliver'] = $billCheckout->getDeliverList($this->bill_array['master'], $this->cust_buy_log );

        if (!$c['deliver']) {
            $this->setBillArray( $c );
        }

        //配送站
        $c['distribution'] = $billCheckout->getDistributionList( $this->bill_array['master'] );

        //配送方式
        $c['send'] = $billCheckout->getSendTypeList( $this->bill_array['master'], $this->cust_buy_log);
        if (!$c['send']) {
            $this->setBillArray( $c );
        }

        //支付方式
        $c['pay'] = $billCheckout->getPayTypeList($this->source, $this->bill_array['master'], $this->cust_buy_log);
        if (!$c['pay']) {
            $this->setBillArray( $c );
        }

        $this->setBillArray( $c );
    }

    /**
     * 查询收货地址，并根据收货地址查询配送站、配送方式和支付方式
     * @throws Exception
     */
    private function loadFromAddress() {

        if (!isset($_REQUEST['deliverID']) || !is_numeric($_REQUEST['deliverID'])) {
            returnJsonData('参数错误', 400);
        }

        //实例订单结算类
        $billCheckout = new billCheckout();

        //查询会员收货地址
        if (!$billCheckout->getDeliver( $this->bill_array['master'], $this->cust_buy_log, $_REQUEST['deliverID'] )) {
            returnJsonData('收货地址信息没有找到，请选择其他收货地址', 404);
        }

        unset($this->bill_array['master']['sendTypeID']);
        unset($this->bill_array['master']['payTypeID']);

        //配送站
        $c['distribution'] = $billCheckout->getDistributionList( $this->bill_array['master'] );

        //配送方式
        $c['send'] = $billCheckout->getSendTypeList( $this->bill_array['master'], $this->cust_buy_log );
        if (!$c['send']) {
            $this->setBillArray( $c );
        }

        //支付方式
        $c['pay'] = $billCheckout->getPayTypeList( $this->source, $this->bill_array['master'], $this->cust_buy_log );
        if (!$c['pay']) {
            $this->setBillArray( $c );
        }

        $this->setBillArray( $c );

    }

    /**
     * 查询配送方式，并根据配送方式查询支付方式
     */
    private function loadFromSend() {

        if (!isset($_REQUEST['send_region_id']) || !is_numeric($_REQUEST['send_region_id'])) {
            returnJsonData('参数错误');
        }

        //实例订单结算类
        $billCheckout = new billCheckout();

        //配送方式
        if (!$billCheckout->getSendType( $this->bill_array['master'], $this->cust_buy_log, $_REQUEST['send_region_id'] )) {
            returnJsonData('配送方式信息没有找到，请选择其他配送方式', 404);
        }

        unset($this->bill_array['master']['payTypeID']);
        unset($this->bill_array['master']['payment_method_id']);

        //支付方式
        $c['pay'] = $billCheckout->getPayTypeList( $this->source, $this->bill_array['master'], $this->cust_buy_log );
        if (!$c['pay']) {
            $this->setBillArray( $c );
        }

        $this->setBillArray( $c );

    }

    /**
     * 查询支付方式信息，并根据支付方式查询付现方式
     * @throws Exception
     */
    private function loadFromPay() {

        if (!isset($_REQUEST['payTypeID']) || !is_numeric($_REQUEST['payTypeID'])) {
            returnJsonData('参数错误');
        }

        //实例订单结算类
        $billCheckout = new billCheckout();

        //支付方式
        if (!$billCheckout->getPayType( $this->bill_array['master'], $this->cust_buy_log, $_REQUEST['payTypeID'])) {
            returnJsonData('支付方式信息没有找到，请选择其他支付方式', 404);
        }
        unset($this->bill_array['master']['payment_method_id']);

        $c = array();
        $this->setBillArray( $c );

    }

    /**
     * 查询付款方式信息
     * @throws Exception
     */
    private function loadFromPayment() {

        if (!isset($_REQUEST['payment_method_id']) || !is_numeric($_REQUEST['payment_method_id'])) {
            returnJsonData('参数错误');
        }

        global $G_SHOP;

        //实例订单结算类
        $billCheckout = new billCheckout( $G_SHOP->DBCA );

        //付款方式
        if (!$billCheckout->getPayment( $this->bill_array['master'], $this->cust_buy_log, $_REQUEST['payment_method_id'])) {
            returnJsonData('付现方式信息没有找到，请选择其他付现方式', 404);
        }

        $c = array();
        $this->setBillArray( $c );

    }

    /**
     * 查询发票信息
     */
    private function loadFromInvoice() {

        if (!isset($_REQUEST['invoiceID']) || !is_numeric($_REQUEST['invoiceID'])) {
            returnJsonData('参数错误');
        }

        global $G_SHOP;

        //实例订单结算类
        $billCheckout = new billCheckout( $G_SHOP->DBCA );

        try {

            //发票
            if (!$billCheckout->getInvoice( $this->bill_array['master'], $this->cust_buy_log, $_REQUEST['invoiceID'] )) {
                throw new Exception('发票信息没有找到，请选择其他发票信息', 404);
            }

            $c = array();
            $this->setBillArray( $c );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                returnJsonData( $e->getMessage(), $e->getCode() );
            } else {
                error_log($e->getMessage());
                returnJsonData( '系统错误', 500 );
            }

        }

    }

    /**
     * 检查商品促销活动、订单促销、计算金额
     */
    private function totalBill() {

        global $G_SHOP;

        $total_array = array(
            'total_points' => 0,                    //积分总数
            'total_amount' => 0,                    //商品总数
            'bill_totalPaid' => 0,                  //商品总金额
            'bill_money' => 0,                      //订单金额
            'deliver_feePaid' => 0,                 //运费
            'total_subtract_money' => 0,           //订单立减金额
            'total_receivable_money' => 0,        //应收总金额
            'total_weight' => 0,                    //总重量
            'bill_coupon_money' => 0,              //优惠券抵扣金额
            'bill_card_money' => 0,                //代金卡抵扣金额
            'bill_points_money' => 0,              //积分抵扣金额
            'bill_accessories_money' => 0,        //配件金额
            'bill_paying_agent_money' => 0,       //代付订单金额
            'bill_balance_money' => 0,             //余额抵扣金额
            'price_array' => array(),              //价格更新数组
            'card_is_invoice'=> 1                  //卡是否开发票
        );

        $return_array = array(
            'goods' => array(),
            'bill_promotion' => array(),
            'total' => $total_array
        );

        quanli_require('module/base/promotion/promotionGoods.class.php');
        quanli_require('module/base/promotion/promotionBill.class.php');
        quanli_require('module/base/customer/quanliCust.class.php');

        //实例化会员类
        $quanliCust = new quanliCust();

        //实例商品促销类
        $promotionGoods = new promotionGoods($G_SHOP->DBCA);

        //实例订单促销类
        $promotionBill = new promotionBill($G_SHOP->DBCA);

        $bill_array = &$this->bill_array;

        $bill_array['cut_rebate_money'] = 0;        //会员等级折扣

        $send_date = $bill_array['master']['send_date']; //配送日期
        $billPromotion = isset($bill_array['master']['billPromotion']) ? $bill_array['master']['billPromotion'] : null; //促销渠道ID
        $cityid = $bill_array['master']['cityid']; //城市ID

        if (isset($bill_array['master']['payTypeID'])) { //支付方式ID
            $payTypeID = $bill_array['master']['payTypeID'];
        } else {
            $payTypeID = 0;
        }
        if (isset($bill_array['master']['payment_method_id'])) { //付款方式
            $payment_method_id = $bill_array['master']['payment_method_id'];

            if(isset($bill_array['master']['card_is_invoice']))
                $total_array['card_is_invoice'] = $bill_array['master']['card_is_invoice'];

        } else {
            $payment_method_id = 0;
        }

        //使用现金卡
        $use_card_array = array();
        if (isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail'])) {
            $use_card_array = $bill_array['use_card']['detail'];
        }

        //使用优惠券
        $use_coupon = 0;
        if (isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])) {
            $use_coupon = 1;
        }

        //获得会员等级信息
        $cust_rank_array = $quanliCust->getCustRank(  $this->pcustID );

        //add by 20141107 allen.qiang FUN-AC-0015 1元饼干订购活动 ---start
        quanli_require('module/base/activity/activityConfig.class.php');
        $activity_config = new activityConfig('yuan1');
        $config_array = $activity_config->config;
        //add by 20141107 allen.qiang FUN-AC-0015 1元饼干订购活动 ---end

        //add by 20141107 sunqiang FUN-AC-0019 9.9元饼干订购活动 ---start
        $activity_config9 = new activityConfig('yuan9');
        $config_array9 = $activity_config9->config;
        //add by 20141107 sunqiang FUN-AC-0019 9.9元饼干订购活动 ---end



        //mod allen.qiang 20141028 农业银行信用卡五折购 start
        quanli_require('module/base/activity/activitySpike.class.php');
        $activityspike=new activitySpike();
        if($billPromotion == $activityspike->billPromotion)//是否秒杀活动
            $cust_rank_array['rate']=1; //会员等级折扣
        else if($billPromotion == $activityspike->billPromotion_lv5)//LV5五折购
            $cust_rank_array['rate']=1; //会员等级折扣
        else if($billPromotion == $activityspike->billPromotion_ny_xyk){//allen.qiang 20141028 农业银行信用卡五折购 add
            //是否含有一磅蛋糕
            $isbool=false;
            $general=$bill_array['goods']['general'];
            foreach($general as &$goods){
                if($goods['spec']=="1磅")
                    $isbool=true;
            }

            if(($bill_array['master']['payTypeID']==$activityspike->payTypeID_ny_xyk || $bill_array['master']['payment_method_id']==$activityspike->paymentID_ny_xyk) && $cityid==110 && $activityspike->nh_xyk_isDate() && $isbool && $activityspike->nh_xyk_num400()>0){ //判断是否是用农业银行信用卡支付且在活动时间内并且是上海站的1磅蛋糕
                if($bill_array['use_points']['bill_points_money']>0 || $use_coupon==1 || (isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail']))){ //农业银行信用卡五折购不能享受现金卡、专享卡、优惠券、红包、积分、会员等级制度
                    $billPromotion=0;
                }else{
                    $cust_rank_array['rate']=1; //会员等级折扣
                }
            }else{
                $billPromotion=0;
            }

        }
        //mod allen.qiang 20141028 农业银行信用卡五折购 end
        //add by 20141106 allen.qiang FUN-AC-0015 1元饼干订购活动 ---start
        else if($billPromotion == $config_array["billPromotion"] || $billPromotion == $config_array9['billPromotion']){ //1元饼干订购活动促销渠道ID
            $cust_rank_array['rate']=1; //会员等级折扣
        }
        //add by 20141106 allen.qiang FUN-AC-0015 1元饼干订购活动 ---end


        //add by 20141120 allen.qiang  FUN-AC-0020-BD建设银行五折购 ---start
        quanli_require('module/base/activity/activityCbc.class.php');
        //实例建设银行五折购活动类
        $activityCBC=new activityCbc();
        $_REQUEST["pcustID"]=$this->pcustID;
        $activity_master=$activityCBC->activity_master($_REQUEST);
        if($billPromotion == $activity_master["billPromotion"] ){
            //是否含有一磅蛋糕
            $isbool=false;
            $general=$bill_array['goods']['general'];
            foreach($general as &$goods){
                if($goods['spec']=="1磅" && $goods['goodsName']!="悦时光")
                    $isbool=true;
            }
            if($bill_array['master']['payment_method_id']==$activity_master["paymentID_CBC"] && $cityid==110 && $activity_master["isDate"]==1 && $isbool && $activity_master["activity_num"]>0){ //判断是否是用建行信用卡支付且在活动时间内并且是上海站的1磅蛋糕
                if($bill_array['use_points']['bill_points_money']>0 || $use_coupon==1 || (isset($bill_array['use_card']['detail']) && !empty($bill_array['use_card']['detail']))){ //建行信用卡五折购不能享受现金卡、专享卡、优惠券、红包、积分
                    $billPromotion=0;
                }
            }else{
                $billPromotion=0;
            }
        }
        //add by 20141120 allen.qiang  FUN-AC-0020-BD建设银行五折购 ---end

        //======================================
        //===============订单商品===============
        //======================================
        if(isset($bill_array['goods']['general']) && !empty($bill_array['goods']['general'])) {

            $goods_array = array();

            foreach($bill_array['goods']['general'] as &$goods){

                //计算配件费用
                $accessories_money = 0;
                if($goods['fittings']){
                    foreach ($goods['fittings'] as $fitting) {
                        $accessories_money += $fitting['buyNum'] * $fitting['price'];
                        //mod by yim.hu FUN-BK-0009  计算应用总金额 start
                        	//$total_array['bill_accessories_money'] += $fitting['buyNum'] * $fitting['price'];
                       // if($fitting['buyMoney']>0){
                        	$total_array['bill_accessories_money'] += $fitting['buyNum'] * $fitting['buyMoney'];
                       // }else{
                        //	$total_array['bill_accessories_money'] += $fitting['buyNum'] * $fitting['price'];
                       // }
                        //mod by yim.hu FUN-BK-0009  计算应用总金额 end
                    }
                }



                $goods['price'] = $goods['salePrice'];

                $goods['goods_promotion'] = null;
                $goods['goods_promotion_info'] = null;

                if ($goods['adjustPrice'] > -1 && $goods['adjustPrice'] != '') { //手工调价

                    $goods['price'] = $goods['adjustPrice'];

                }
                elseif(isset($_REQUEST['bill_type']) && !empty($_REQUEST['bill_type']) && in_array($_REQUEST['bill_type'],array(2,3,5,7,9))){//特殊订单类型 add by allen.qiang 2015-06-24

                    $goods['price'] = '0.00';

                }
                else { //商品促销活动

                    $promotion_array = $promotionGoods->searchGoodsPromotion($goods['postID'], $send_date, $billPromotion, $cityid, $payTypeID, $use_card_array, $use_coupon, $payment_method_id, $cust_rank_array['rankID'] );

                    if(isset($this->bill_array['master']['foretaste']) && $this->bill_array['master']['foretaste'] == 1){
                        $promotion_array = null;
                    }

                    $goods_promotion = array();

                    if ($promotion_array) {
                        $goods['goods_promotion'] = $promotion_array;
                        $goods_promotion = array();
                        foreach($promotion_array as &$promotion_goods) {
                            switch($promotion_goods['type']) {
                                case 1: //商品立减
                                    $goods['price'] -= $promotion_goods['money'];
                                    $goods_promotion[] = '[立减]' . $promotion_goods['remark'];
                                    break;
                                case 2:  //商品特价
                                    $goods['price'] = $promotion_goods['money'];
                                    $goods_promotion[] = '[特价]' . $promotion_goods['remark'];
                                    break;
                                case 6: //商品打折
                                    $goods['price'] = round($goods['price'] * $promotion_goods['money'], 2);
                                    $goods_promotion[] = '[折扣]' . $promotion_goods['remark'];
                                    break;
                            }
                        }

                        if ($goods['price'] < 0) {
                            $goods['price'] = 0;
                        }
                        $goods['goods_promotion_info'] = implode('<br>', $goods_promotion);

                    }

                    $goods_price = $goods['price'];
                    $goods['price'] = round($goods['price'] * $cust_rank_array['rate'], 2);

                    //会员折扣扣减金额
                    $bill_array['cut_rebate_money'] += ($goods_price - $goods['price']) * $goods['goods_amount'];

                }


   
		        //add by yim.hu WEB-0002 FUN-BK-0009_配送单优化 start
                $ebsigHandler = new quanliGoods( $G_SHOP->DBCA );
                $sale_array = array(
                	'postID' => $goods['postID']
                );
                $saleGoods = $ebsigHandler->searchGoodsSale( $sale_array );
                if($saleGoods[0]['deliverSpace'] == 1){
					$goods_promotion[] = "<span style='color:blue'>需提前24小时订购</span>";
					$goods['goods_promotion_info']= implode('<br>', $goods_promotion);
                }				
                //add by yim.hu WEB-0002 FUN-BK-0009_配送单优化 end
				
                $total_array['price_array'][$goods['postID']] = array(
                    'price' => $goods['price'],
                    'total_amount' => $goods['price'] * $goods['goods_amount']
                );


                $total_array['total_amount'] += $goods['goods_amount'];
                $total_array['bill_totalPaid'] += $goods['price'] * $goods['goods_amount'];

                $goods_array[] = array(
                    'postID' => $goods['postID'],
                    'price' => $goods['price'] + $accessories_money,
                    'goods_amount' => 1,
                );

            }

            if (!isset($this->bill_array['master']['deliver_fee'])) {
                $this->bill_array['master']['deliver_fee'] = 0;
            }

            //mod 20141124 sunqiang  FUN-BK-0034 运费规则调整 start
            if($this->bill_array['master']['billPlatform'] == 1)
            {
                $total_array['deliver_feePaid'] = $this->bill_array['master']['deliver_feePaid'];
            }
            else
            {
                $total_array['deliver_feePaid'] = $this->bill_array['master']['deliver_fee'];
                $this->bill_array['master']['deliver_feePaid'] = $this->bill_array['master']['deliver_fee'];
            }

            //$total_array['deliver_feePaid'] = $this->bill_array['master']['deliver_fee']; //运费

            //mod 20141124 sunqiang FUN-BK-0034 运费规则调整 end


            //检查订单促销活动
            $bill_promotion_array = $promotionBill->searchBillPromotion( $goods_array, $send_date, $billPromotion, $cityid, $payTypeID, $use_card_array, $use_coupon, $payment_method_id, $cust_rank_array['rankID'] );

            $bill_promotion_info_array = array();

            if(isset($this->bill_array['master']['foretaste']) && $this->bill_array['master']['foretaste'] == 1){
                $bill_promotion_array = null;
            }

            //add by sunqiang LV5五折购 ---start
            if(isset($bill_array['master']['billPromotion']) && $bill_array['master']['billPromotion'] == $activityspike->billPromotion_lv5)
            {
                $bill_promotion_array = null;
            }
            //add by sunqiang lv5会员新加提示信息 ---end

            if (isset($bill_promotion_array['meet'])) {

                foreach ($bill_promotion_array['meet'] as &$bill_promotion) {

                    switch($bill_promotion['type']) {

                        case 1: //订单立减
                            $total_array['total_subtract_money'] += $bill_promotion['subtractMoney'];
                            $bill_promotion_info_array[] = '[立减]' . $bill_promotion['remark'];
                            break;

                        case 2: //免运费
                            $total_array['deliver_feePaid'] = 0;
                            $bill_promotion_info_array[] = '[免运费]' . $bill_promotion['remark'];
                            break;

                        case 3: //赠送优惠券
                            $bill_promotion_info_array[] = '[赠券]' . $bill_promotion['remark'];
                            break;

                        case 4: //订单打折
                            $total_array['bill_totalPaid'] = round($total_array['bill_totalPaid'] * $bill_promotion['subtractMoney'], 2);
                            $total_array['bill_accessories_money'] = round($total_array['bill_accessories_money'] * $bill_promotion['subtractMoney'], 2);
                            $bill_promotion_info_array[] = '[打折]' . $bill_promotion['remark'];
                            break;
                    }

                }

                $bill_array['bill_promotion'] = $bill_promotion_array['meet'];

            }else{
                $bill_array['bill_promotion'] = null;
            }

            $return_array['bill_promotion'] = $bill_promotion_info_array;

            //修改运费
            if(isset($bill_array['alter_freight']) && $bill_array['alter_freight'] != '') {

                $total_array['deliver_feePaid'] = floatval($bill_array['alter_freight']);

            }

        } else {

            $bill_array['goods']['general'] = array();

        }
        //======================================
        //===============订单商品===============
        //======================================

        //积分抵扣金额
        if (isset($bill_array['use_points'])) {
            $total_array['bill_points_money'] = $bill_array['use_points']['bill_points_money'];
        }

        //余额抵扣金额
        if (isset($bill_array['use_balance'])) {
            $total_array['bill_balance_money'] = $bill_array['use_balance']['balance'];
        }

        //代金卡抵扣金额
        if (isset($bill_array['use_card']) && count($bill_array['use_card']['detail']) > 0) {
            foreach($bill_array['use_card']['detail'] as $card){
                $total_array['bill_card_money'] += $card['deducation'];
            }
        }

        //优惠券抵扣金额
        if (isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])) {
            foreach ($bill_array['use_coupon'] as &$coupon) {
                $total_array['bill_coupon_money'] += $coupon['amount'];
            }
        }

        //代付订单金额
        if (isset( $bill_array['bill_paying_agent']) && !empty( $bill_array['bill_paying_agent'])) {
            foreach ( $bill_array['bill_paying_agent'] as &$agent) {
                $total_array['bill_paying_agent_money'] += $agent['bill_receivable_money'];
            }
        }

        //系统订单金额的算法修改
        //add by guojun.song 2015-05-12 100-MK-FUN-BK-006-订单中金额算法&支付状态调整   start
            if(isset($_REQUEST['bill_type']) && !empty($_REQUEST['bill_type'])){
            switch($_REQUEST['bill_type']) {
                case 3: //市场推广类型      商品标价+配件总额+运费-促销金额-补偿的订单总金额（补偿的商品的标价+配件总额+运费）
                    $total_array['bill_money'] = $total_array['bill_totalPaid']
                        + $total_array['bill_accessories_money']
                        + $this->bill_array['master']['deliver_fee']
                        - $billPromotion
                        - ($total_array['bill_totalPaid'] + $total_array['bill_accessories_money'] + $this->bill_array['master']['deliver_fee']);
                    break;
                case 5: //补偿订单类型      商品标价+配件总额+运费-促销金额-补偿的订单总金额（补偿的商品的标价+配件总额+运费）
                    $total_array['bill_money'] = $total_array['bill_totalPaid']
                        + $total_array['bill_accessories_money']
                        + $this->bill_array['master']['deliver_fee']
                        - $billPromotion
                        - ($total_array['bill_totalPaid'] + $total_array['bill_accessories_money'] + $this->bill_array['master']['deliver_fee']);
                    break;
                case 7: //招待赠送订单类型   商品标价+配件总额+运费-促销金额-招待赠送的订单的总金额（招待赠送的商品的标价+配件总额+运费）
                    $total_array['bill_money'] = $total_array['bill_totalPaid']
                        + $total_array['bill_accessories_money']
                        + $this->bill_array['master']['deliver_fee']
                        - $billPromotion
                        - ($total_array['bill_totalPaid'] + $total_array['bill_accessories_money'] + $this->bill_array['master']['deliver_fee']);
                    break;
                case 9: //试吃订单类型       商品标价+配件总额+运费-促销金额-试吃的订单的总金额(试吃商品的标价+配件总额+运费)
                    $total_array['bill_money'] = $total_array['bill_totalPaid']
                        + $total_array['bill_accessories_money']
                        + $this->bill_array['master']['deliver_fee']
                        - $billPromotion
                        - ($total_array['bill_totalPaid'] + $total_array['bill_accessories_money'] + $this->bill_array['master']['deliver_fee']);
                    break;
                default:
                    //================================================
                    //订单金额 = 商品金额  + 配件金额 + 代付金额
                    //================================================
                    $total_array['bill_money'] = $total_array['bill_totalPaid']
                        + $total_array['bill_accessories_money']
                        + $total_array['bill_paying_agent_money'];
                    break;


            }
        }else{
            $total_array['bill_money'] = $total_array['bill_totalPaid']
                + $total_array['bill_accessories_money']
                + $total_array['bill_paying_agent_money'];
        }
        //by guojun.song 2015-05-12 100-MK-FUN-BK-006-订单中金额算法&支付状态调整     end



        //================================================
        //订单金额 = 商品金额 + 运费 + 配件金额 + 代付金额
        //================================================


        //订单应收金额（商品实收金额 + 配件金额 + 运费 + 代付订单金额 - 订单立减金额 - 优惠劵抵扣金额 - 代金卡抵扣金额 - 积分抵扣金额）
        $total_array['total_receivable_money'] = $total_array['bill_money']
            - $total_array['total_subtract_money']
            - $total_array['bill_coupon_money']
            - $total_array['bill_card_money']
            - $total_array['bill_points_money']
            - $total_array['bill_balance_money'];

        if( $total_array['total_receivable_money'] <= 0){
            $total_array['total_receivable_money'] = 0.00;
        }

        $total_array['bill_money'] += $total_array['deliver_feePaid'];

        $total_array['total_receivable_money'] += $total_array['deliver_feePaid'];

        //去零取整  edit by wanglulu 2015/01/09  start
        if( IS_REMOVE_DECIMALS && intval($total_array['total_receivable_money']) != $total_array['total_receivable_money'] ){
            $total_array['total_receivable_money'] = intval( $total_array['total_receivable_money'] );
        }
        //去零取整  edit by wanglulu 2015/01/09  end

        //试吃订单
        if(isset($this->bill_array['master']['foretaste']) && $this->bill_array['master']['foretaste'] == 1){
            $total_array['total_receivable_money'] = 0.00;
            //$total_array['deliver_feePaid'] = 0;
            $total_array['total_subtract_money'] = 0;
            $total_array['bill_accessories_money'] = 0;
        }

        //积分等于应收金额/4
        $total_array['total_points'] = floor($total_array['total_receivable_money']/4);

        $return_array['goods'] = $bill_array['goods']['general'];
        $return_array['total'] = $total_array;

        //市场推广类型、补偿订单类型、招待赠送订单类型、试吃订单类型 add by allen.qiang 2015-06-12
        if(isset($_REQUEST['bill_type']) && !empty($_REQUEST['bill_type']) && in_array($_REQUEST['bill_type'],array(3,5,7,9))){
            foreach($return_array['goods'] as $k=>$val){
                $return_array['goods'][$k]['price'] = '0.00';
            }
        }


        $this->setBillArray(null, $return_array);

    }

    /*
     * 使用优惠券
     */
    private function useCoupon() {

        global $G_SHOP;

        if (!isset($_REQUEST['code']) || empty($_REQUEST['code'])) {
            returnJsonData('请输入优惠券编码');
        }

        //加载类文件
        quanli_include('module/base/promotion/quanliCoupon.class.php');

        //实例优惠券类
        $ebsigCoupon = new ebsigCoupon( $G_SHOP->DBCA );

        $code = $_REQUEST['code'];
        $bill_array = & $this->bill_array;

        /**
         * =====================================
         * 生成商品数组
         * =====================================
         */
        $goods_array = array();

        if (isset($bill_array['goods']['general']) && !empty($bill_array['goods']['general'])) {
            foreach ($bill_array['goods']['general'] as &$list) {
                $goods_array[] = array(
                    'postID' => $list['postID'],
                    'price' => $list['price'],
                    'cityID'=> $list['cityID'],
                    'goodsAmount' => 1
                );
            }
        } else {
            returnJsonData('请先添加商品', 404);
        }
        /**
         * =====================================
         * 生成商品数组
         * =====================================
         */

        //检查优惠券
        $result_array = $ebsigCoupon->checkCoupon($code, $this->pcustID, $goods_array);

        if ($result_array['code'] == 200) {

            $coupon = array(
                'code' => $result_array['data']['code'],
                'amount' => $result_array['data']['amount'],
                'couponID' => $result_array['data']['couponID'],
                'couponType' => $result_array['data']['couponType'],
                'couponName' => $result_array['data']['couponName'],
                'useType' => $result_array['data']['useType']
            );

            //检查优惠券类型使用情况
            if(isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon']) && $coupon['useType'] == 1){

                $redCount = 0;
                foreach($bill_array['use_coupon'] as &$coupon){

                    if($coupon['useType'] == 1){
                        $redCount++;
                        break;
                    }
                }

                if($redCount > 0){
                    returnJsonData('此类型优惠券只能使用一次，请换成其他类型优惠券使用');
                }

            }

            $bill_array['use_coupon'][$coupon['code']] = $coupon;
            $this->setBillArray(null, $coupon );

        } else {
            returnJsonData( $result_array['message'], $result_array['code'] );
        }

    }

    /**
     * 取消使用优惠券
     */
    private function cancelCoupon() {

        if(!isset($_REQUEST['code']) || empty($_REQUEST['code'])){
            returnJsonData('取消使用优惠券编码不能为空');
        }

        $code = $_REQUEST['code'];
        $use_coupon = &$this->bill_array['use_coupon'];

        if(!isset($use_coupon[$code])){
            returnJsonData('优惠券已经取消，无需再次取消');
        }

        unset($use_coupon[$code]);

        $this->setBillArray(null,$code);

    }

    /**
     * 检查促销渠道
     */
    private function promotionChannel(){

        //加载类文件
        quanli_include('module/base/promotion/quanliCard.class.php');
        quanli_include('module/base/promotion/quanliCoupon.class.php');

        //实例优惠券类
        $ebsigCoupon = new quanliCoupon();

        //实例化现金卡类
        $quanliCard = new quanliCard();

        //返回数组
        $return_array = array(
            'card_array' => array(),
            'coupon_code'=> ''
        );

        $this->bill_array['master']['billPromotion'] = $_REQUEST['billPromotion'];

        if(!isset($this->bill_array['goods']['general'])){

            $this->setBillArray(null,$return_array);

        }

        //检查现金卡
        foreach($this->bill_array['goods']['general'] as &$goods) {
            $goods['use_card'] = array();
            $goods['card_deducation'] = 0;
        }

        if(isset($this->bill_array['use_card']['detail'])){
            $use_card = &$this->bill_array['use_card']['detail'];

            if (count($use_card) > 0) {
                $new_use_card_array = array(
                    'balance' => 0,
                    'detail' => array()
                );

                foreach($use_card as &$card) {

                    //验证是否已经使用
                    $result_array = $quanliCard->checkCard( $card['card_pwd'], $this->bill_array['goods']['general'], $new_use_card_array );
                    if($result_array['code'] == 200){
                        $card_pwd = $result_array['data'];
                        $this->bill_array['card_array'][$card_pwd] = $card_pwd;
                    }
                }
                $this->bill_array['use_card'] = $new_use_card_array;
                $return_array['card_array'] = $new_use_card_array['detail'];

            }

        }

        $this->setBillArray(null,$return_array);

    }



    /**
     * 使用积分
     */
    private function usePoints(){

        if(!isset($_REQUEST['points']) || empty($_REQUEST['points'])){
            returnJsonData('请输入要抵扣的金额');
        }

        if(!is_money($_REQUEST['points'])){
            returnJsonData('输入的金额不正确，请重新输入');
        }

        if($_REQUEST['points'] == 0){
            returnJsonData('输入的金额不能为0');
        }

        if(!is_numeric($_REQUEST['points']) || $_REQUEST['points'] < 0){
            returnJsonData('输入的金额必须为非负整数');
        }

        quanli_require('module/func/eai.func.php');

        $ebsigEai = eai_crm();
        $result = $ebsigEai->searchCustAccount($this->pcustID, G_POINTS_ID);

        $points = $_REQUEST['points'] * 100;

        if ($result['code'] == 200) {
            $useableAccount = $result['data']['useableAccount'];
            if($points > $useableAccount){
                returnJsonData('账户积分不足');
            }
        } else {
            returnJsonData($result['message'], $result['code']);
        }

        //记录积分使用信息
        $this->bill_array['use_points'] = array(
            'points' => $points,
            'bill_points_money' => $_REQUEST['points']
        );

        $this->setBillArray(null, $this->bill_array['use_points']);

    }

    /**
     * 取消使用积分
     */
    private function cancelPoints(){

        if(!isset($this->bill_array['use_points']) || empty($this->bill_array['use_points'])){
            returnJsonData('参数错误');
        }

        if(isset($this->bill_array['use_points'])){
            unset($this->bill_array['use_points']);
        }

        $this->setBillArray();

    }

    /**
     * 使用现金卡
     */
    private function useCard() {

        global $G_SHOP;

        if (!isset($_REQUEST['card_pwd']) || empty($_REQUEST['card_pwd'])) {
            returnJsonData('请输入卡密码');
        }

        if (!isset($this->bill_array['goods']['general']) || empty($this->bill_array['goods']['general'])) {
            returnJsonData('请先添加商品');
        }

        $card_pwd = $_REQUEST['card_pwd'];

        if (isset($this->bill_array['card_array'][$card_pwd])) {
            returnJsonData('该现金卡已使用');
        }

        if (isset($this->bill_array['use_card']['balance']) && $this->bill_array['use_card']['balance'] > 0) {
            returnJsonData('没有可供现金卡抵用金额的商品');
        }

        //加载类文件
        quanli_include('module/base/promotion/quanliCard.class.php');

        //实例化现金卡类
        $quanliCard = new quanliCard( $G_SHOP->DBCA );

        if (!isset($this->bill_array['use_card'])) {

            $this->bill_array['use_card'] = array(
                'balance' => 0,
                'detail' => array()
            );

        }

        //验证是否已经使用
        $result_array = $quanliCard->checkCard( $card_pwd, $this->bill_array['goods']['general'], $this->bill_array['use_card'], $_REQUEST['bill_no'] );
        if ($result_array['code'] == 200) {

            $this->bill_array['card_array'][$card_pwd] = $card_pwd;
            $this->setBillArray(null, array('card_pwd' => $card_pwd, 'list' => $this->bill_array['use_card']['detail']));

        } else {
            returnJsonData( $result_array['message'], $result_array['code'] );
        }

    }

    /**
     * 取消使用代金卡
     */
    private function cancelCard(){

        global $G_SHOP;

        if(!isset($_REQUEST['card_pwd']) || empty($_REQUEST['card_pwd'])){
            returnJsonData('参数错误');
        }
        $card_pwd = $_REQUEST['card_pwd'];

        //加载类文件
        quanli_include('module/base/promotion/quanliCard.class.php');

        //实例化现金卡类
        $quanliCard = new quanliCard( $G_SHOP->DBCA );

        if(!isset($this->bill_array['use_card']['detail'][$card_pwd])){

            returnJsonData('ok', 200, $this->bill_array['use_card']['detail']);

        }
        $use_card = &$this->bill_array['use_card']['detail'];

        //删除代金卡
        unset($use_card[$card_pwd]);
        unset($this->bill_array['card_array'][$card_pwd]);

        foreach($this->bill_array['goods']['general'] as &$goods) {

            $goods['use_card'] = array();
            $goods['card_deducation'] = 0;
        }

        $new_use_card_array = array(
            'balance' => 0,
            'detail' => array()
        );

        if (count($use_card) > 0) {

            foreach($use_card as &$card) {

                //验证是否已经使用
               $result_array = $quanliCard->checkCard( $card['card_pwd'], $this->bill_array['goods']['general'], $new_use_card_array );

                if($result_array['code'] == 200){
                    $card_pwd = $result_array['data'];
                    $this->bill_array['card_array'][$card_pwd] = $card_pwd;
                }

            }
        }
        $this->bill_array['use_card'] = $new_use_card_array;

        $this->setBillArray(null, array('card_pwd' => $card_pwd, 'list' => $new_use_card_array['detail']));

    }

    /**
     * 检测代付订单
     */
    private function checkBillPayingAgent(){

        if(!isset($_REQUEST['paying_agent_code']) || empty($_REQUEST['paying_agent_code'])){
            returnJsonData('请输入代付订单编号');
        }

        //引入订单查询类
        quanli_require('module/base/bill/billSearch.class.php');

        //实例化订单查询类
        $billSearch = new billSearch();

        $paying_agent_code = $_REQUEST['paying_agent_code'];

        //验证代付订单号的信息
        $arg_array = array(
            'bill_code' => $paying_agent_code
        );
        $bill_master_array = $billSearch->searchBillInfo($arg_array);
        if(!$bill_master_array){
            returnJsonData('订单信息没有找到');
        }

        $bill_master_array = $bill_master_array[0];
        if (in_array($bill_master_array['bill_status'], array(2, 3, 4, 5, 6, 7, 8))) {
            returnJsonData('订单已生产，无法代付');
        }
        if ($bill_master_array['bill_receivable_money'] <= 0) {
            returnJsonData('订单无可代付的金额');
        }

        //查询代付订单
        $arg_array = array(
            'bill_no' => $bill_master_array['bill_no']
        );
        $bill_paying_agent_array = $billSearch->searchBillPayingAgent($arg_array);
        if ($bill_paying_agent_array) {
            returnJsonData('订单已经已经被代付');
        }

        $this->bill_array['bill_paying_agent'][$paying_agent_code] = array (
            'bill_no' => $bill_master_array['bill_no'],
            'bill_code' => $paying_agent_code,
            'deliver_name' => $bill_master_array['deliver_name'],
            'bill_receivable_money' => $bill_master_array['bill_receivable_money']
        );

        $this->setBillArray(null, array('bill_code' => $paying_agent_code, 'list' => $this->bill_array['bill_paying_agent']));

    }

    /**
     * 取消代付订单
     */
    private function delBillPayingAgent() {

        //检验参数
        if (!isset($_REQUEST['paying_agent_code']) || empty($_REQUEST['paying_agent_code'])) {
            returnJsonData('缺少参数');
        }

        //代付订单编号
        $paying_agent_code = $_REQUEST['paying_agent_code'];

        if (isset($this->bill_array['bill_paying_agent'][$paying_agent_code])) {
            unset($this->bill_array['bill_paying_agent'][$paying_agent_code]);
        }

        $this->setBillArray(null, $paying_agent_code);

    }

    /**
     * 高级客服授权
     * @param   userID
     * @param   userPwd
     * @param   code
     * @param   sign
     * @return  array
     * @author create by allen.qiang
     */
    private function serviceAccredit(){

        //验证参数
        if(!isset($_REQUEST['userID'], $_REQUEST['userPwd'], $_REQUEST['code'])){
            returnJsonData('缺少参数');
        }

        if(empty($_REQUEST['code'])){
            returnJsonData('参数错误');
        }

        if(empty($_REQUEST['userID'])){
           returnJsonData('用户名不能为空');
        }

        if(empty($_REQUEST['userPwd'])){
            returnJsonData('用户密码不能为空');
        }

        $code = $_REQUEST['code'];

        /**
         * 高级客服|澳粒高级客服 权限id
         * 1004  高级客服权限id
         * 1022  澳粒高级客服权限id
         */

        $permission_id = 1004;
        if(isset($_REQUEST['sign']) && $_REQUEST['sign'] == 'al'){
            $permission_id = 1026;
        }

        global $G_SHOP;

        quanli_require("module/base/system/sysUser.class.php");
        quanli_require("module/base/system/sysRole.class.php");

        //实例化后台用户类
        $sysUser = new sysUser($G_SHOP->DBCA);
        $sysRole = new sysRole($G_SHOP->DBCA);

        //查询验证后台用户
        $arg_array = array(
            'userID' => $_REQUEST['userID']
        );
        $user_array = $sysUser->searchUserInfo($arg_array);
        if (!$user_array) {
            returnJsonData('用户不存在');
        }
        if ($user_array[0]['userPwd'] != md5($_REQUEST['userPwd'])) {
            returnJsonData('密码错误');
        }

        //查询用户的角色
        $arg_array = array(
            'userID' => $_REQUEST['userID']
        );
        $user_userrole_array = $sysUser->searchUserRole($arg_array);

        if(!$user_userrole_array){
            returnJsonData('角色不存在');
        }

        $isP = 0;
        foreach ($user_userrole_array as &$role) {
            //查询角色下的权限
            $arg_array = array(
                'roleID' => $role
            );
            $user_rolepermission_array = $sysRole->searchRolePermission($arg_array);
            if(isset($user_rolepermission_array[$permission_id]) && $user_rolepermission_array[$permission_id] == 1){
                $isP++;
            }
        }

        if(!$isP){
            returnJsonData('没有权限');
        }

        $G_SHOP->sessionCache_set('AUTH_' . $code, 1, 3600,true);

        returnJsonData('ok', 200);

    }

    /**
     * 修改运费
     */
    private function alterFreight(){

        global $G_SHOP;

        if(isset($_REQUEST['alterFreight']) && !empty($_REQUEST['alterFreight']) && !is_money($_REQUEST['alterFreight'])){
            returnJsonData('输入的金额不正确，请重新输入');
        }

        if(!isset($_REQUEST['code']) || empty($_REQUEST['code'])){
            returnJsonData('参数错误');
        }

        //验证
        $result = $G_SHOP->sessionCache_get( 'AUTH_' . $_REQUEST['code'], true );

        if(!$result)
            returnJsonData('权限不够');


        $this->bill_array['alter_freight'] = $_REQUEST['alterFreight'];

        $this->setBillArray();

    }

    /**
     * 使用余额
     */
    private function useBalace(){

        if(!isset($_REQUEST['balance']) || empty($_REQUEST['balance'])){
            returnJsonData('请输入余额');
        }

        if(!is_money($_REQUEST['balance'])){
            returnJsonData('输入的金额不正确，请重新输入');
        }

        $balance = $_REQUEST['balance'];

        quanli_require('module/func/eai.func.php');

        $ebsigEai = eai_crm();
        $result = $ebsigEai->searchCustAccount($this->pcustID,G_CASH_ID);

        if($result['code'] == 200){
            $useableAccount = $result['data']['useableAccount'];
            if($balance > $useableAccount){
                returnJsonData('账户余额不足');
            }
        }else{
            returnJsonData($result['message'], $result['code']);
        }

        //记录余额使用信息
        $this->bill_array['use_balance'] = array(
            'balance' => $balance,
        );

        $this->setBillArray(null, $this->bill_array['use_balance']);

    }

    /**
     * 取消使用余额
     */
    private function cancelUseBalance(){

        if(!isset($this->bill_array['use_balance']) || empty($this->bill_array['use_balance'])){
            returnJsonData('参数错误');
        }

        if(isset($this->bill_array['use_balance'])){
            unset($this->bill_array['use_balance']);
        }

        $this->setBillArray();

    }

}

